package org.rambadger.command.resource;

import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
import com.yammer.dropwizard.auth.Auth;
import com.yammer.dropwizard.jersey.params.IntParam;
import org.mongojack.DBCursor;
import org.mongojack.DBSort;
import org.mongojack.JacksonDBCollection;
import org.rambadger.command.auth.AuthUser;
import org.rambadger.command.axon.JCollection;
import org.rambadger.command.providers.Pagination;
import org.rambadger.command.representation.User;
import org.rambadger.command.view.UserView;
import org.rambadger.command.view.UsersView;

import javax.annotation.Nullable;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.List;

@Path("/users")
public class ViewUsersResource {
    @JCollection(type=User.class)
    private JacksonDBCollection<User, String> users = null;

    @GET
    @Produces({MediaType.TEXT_HTML,MediaType.APPLICATION_JSON})
    public Object getUserList(@Auth(required = true) AuthUser user, @Context Pagination userPagi) {
//        int perPage = userPerPage.get();
//        if (perPage < 0 || 100 < perPage) {
//            return Response.status(Response.Status.INTERNAL_SERVER_ERROR);
//        }
        DBCursor<User> found = users.find().sort(DBSort.asc("_id"));
        //int usersTotal = users.find().count();
        //int pagesTotal = (int) Math.ceil((double)usersTotal / (double)usersPerPage.get());
        found.limit(userPagi.perPage).skip((userPagi.page-1)*userPagi.perPage);

        List<UserView> usersFound = FluentIterable.from(found).transform(new Function<User, UserView>() {
            @Nullable @Override
            public UserView apply(@Nullable User input) {
                return new UserView(null, input);
            }
        }).toList();
        found.close();

        if (userPagi.page > 1)
            return new UsersView(user, usersFound);

        else
            return new UsersView(user, usersFound);

    }

}
